<?php

namespace app\games\controller;

use think\Controller;
use think\Request;
use think\Log;

class Vip extends Controller
{
    protected $VipModel = null;
    protected $PayModel = null;
    protected $UserModel = null;
    protected $OrderModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->VipModel = model('common/Games/Gamevip');
        $this->PayModel = model('common/Pay/Pay');
        $this->UserModel = model('common/Games/Gameuser');
        $this->OrderModel = model('common/Games/Gameorder');
    }

    public function getviplist()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $where = [];

            if ($params['id']) {
                $where['id'] = $params['id'];
            }

            $res = $this->VipModel->where($where)->select();

            $data = [
                'viplist' => $res,
            ];

            if ($res) {
                $this->success('查询成功', "", $data);
            } else {
                $this->error($this->VipModel->getError());
            }
        }
    }

    // 购买vip
    public function buyvip()
    {
        $vipid = $this->request->param('vipid', 0, 'trim'); //套餐id
        $busid = $this->request->param('busid', 0, 'trim'); //用户id
        $type = $this->request->param('type', 'wx', 'trim'); //支付类型，微信还是支付宝
        $money = null;

        $vip = $this->VipModel->find($vipid);
        $bus = $this->UserModel->find($busid);

        if (!$bus) {
            $this->error('用户不存在');
        }

        if (!$vip) {
            $this->error('套餐已不存在');
        } else {
            $money = floatval($vip['money']);
        }

        if ($money <= 0) {
            $this->error('套餐金额错误');
        }

        // 组装支付订单信息
        $PayData = [
            'name' => '会员充值',
            'third' => ['busid' => $busid],
            'type' => $type,
            'total' => $money,
            'cashier' => 1,
            'jump' => '/games/vip/jump',
            'notice' => '/games/vip/notice', // 处理支付成功后业务逻辑
        ];

        // 调用模型的支付方法 => 直接调用创建订单接口
        $result = $this->PayModel->payment($PayData);

        if (json_decode($result, true)) {
            $result = json_decode($result, true);

            if (json_decode($result['third'], true)) {
                $result['third'] = json_decode($result['third'], true);
                $this->success('订单创建成功', '', $result);
            }
        } else {
            $this->error($result, '', $result);
        }
    }

    // 支付状态更新
    public function status()
    {
        if ($this->request->isPost()) {
            $payid = $this->request->param('payid', 0, 'trim');

            $pay = $this->PayModel->find($payid);

            if (!$pay) {
                // 写入日志
                Log::error('支付订单不存在');

                $this->error('支付订单不存在');
            }

            switch ($pay['status']) {
                case 0:
                    $this->error('订单未支付', null, $pay);
                    break;

                case 1:
                    $this->success('订单已支付', null, $pay);
                    break;

                case 2:
                    $this->error('订单已关闭', null, $pay);
                    break;
            }
        }
    }

    // 成功跳转
    public function jump()
    {
        $this->success('支付成功', url('/home/business/index'));
    }

    // 支付回调处理
    public function notice()
    {
        $params = $this->request->param(); //接收回调的所有参数

        $payid = $params['id']; //从全部参数里面获取订单id

        $pay = $this->PayModel->find($payid);

        if (!$pay) {
            $this->error('支付订单不存在');
        }

        // 获取充值金额
        $total = $pay['total'] ?? 0;
        $total = floatval($total);

        if ($total <= 0) {
            $this->error('充值金额不能小于0');
        }

        //将返回数组里面的$third转换为json数组
        $third = isset($pay['third']) ? json_decode($pay['third'], true) : [];

        // 获取下单用户id
        $busid = $third['busid'] ?? 0;

        $business = $this->UserModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
        }

        // 开启事务
        $this->UserModel->startTrans();
        $this->OrderModel->startTrans();

        // 获取vip的详情信息
        $vipinfo = $this->VipModel->where('money', $total)->find();
        $business = $this->UserModel->find($busid);

        if(!$vipinfo)
        {
            $this->error('会员信息不存在');
        }

        if(!$business)
        {
            $this->error('用户不存在');
        }

        $orderinfo =[
            'gameuserid' => $busid,
            'vipid' => $vipinfo['id'],
            'total' => $total,
            'code' => $pay['code'],
            'auto' => 1,
            'outcome' => '审核成功',
        ];

        $order = $this->OrderModel->save($orderinfo);
        if(!$order)
        {
            $this->error('订单创建失败');
        }

        $userinfo =[
            'id' => $busid,
        ];

        if($business['vipendtime'] && $business['vipendtime'] > time())
        {
            $userinfo['vipendtime'] = $business['vipendtime'] + $vipinfo['times'];
        }else{
            $userinfo['vipendtime'] = time() + $vipinfo['times'];
        }

        $user = $this->UserModel->isUpdate(true)->save($userinfo);
        if(!$user)
        {
            $this->UserModel->rollback();
            $this->OrderModel->rollback();
            $this->error('充值失败，有疑问请联系售后');
        }else{
            $this->UserModel->commit();
            $this->OrderModel->commit();
            $this->success('充值成功');
        }
    }

    // 状态管理，设置为取消，status为2
    public function fixstatus()
    {
        $payid = $this->request->param('payid', 0, 'trim');

        $pay = $this->PayModel->find($payid);

        if (!$pay) {
            $this->error('支付订单不存在');
        }

        $data=[
            'id' => $payid,
            'status' => 2,
        ];

        $res = $this->PayModel->isUpdate(true)->save($data);

        if($res)
        {
            $this->success('订单过去更改成功', '', $pay);
        }
        else
        {
            $this->error($this->PayModel->getError());
        }
    }

}
